package org.sandbox2.domain.loan;

import org.sandbox2.util.CalendarUtil;
import org.springframework.roo.addon.entity.RooEntity;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.transaction.annotation.Transactional;

@RooJavaBean
@RooToString
@RooEntity(inheritanceType = "JOINED")
public class InterestOnlyLoan extends Loan {
	
	@Transactional
    public void create() {
    	createPaymentDetails();
        persist();
    }
    
    private void createPaymentDetails() {
        System.out.println("!!!!! createPaymentDetails !!!!!");
        Double balanceOfPrincipal = principal;
        for (int i = 0; i < paymentTime; i++) {
            PaymentDetail paymentDetail = new PaymentDetail();
            paymentDetail.setPaymentTime(i + 1);
            paymentDetail.setPaymentDate(CalendarUtil.addMonth(startDate, i));
            paymentDetail.setInterest((long) Math.floor(balanceOfPrincipal * rate / 1200));
            if (paymentDetail.getPaymentTime().equals(this.paymentTime)) {
            	paymentDetail.setPrincipal(principal.longValue());	
            } else {
                paymentDetail.setPrincipal(0L);
            }
            paymentDetail.setAmount(paymentDetail.getInterest() + paymentDetail.getPrincipal());
            paymentDetail.setBalanceOfPrincipal((balanceOfPrincipal - paymentDetail.getPrincipal()));
            balanceOfPrincipal = paymentDetail.getBalanceOfPrincipal();
            addPaymentDetail(paymentDetail);
            System.out.println(paymentDetail);
        }
    }

    private void addPaymentDetail(PaymentDetail paymentDetail) {
        paymentDetails.add(paymentDetail);
    }

}
